<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="88px">
      <el-form-item label="类别名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态：" prop="showStatus" width="120">
        <el-select
          v-model="queryParams.showStatus"
          placeholder="请选择显示状态"
          clearable
          size="small"
        >
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['mall:category:add']"
        >新增</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['mall:category:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['mall:category:export']"
        >导出</el-button>
      </el-col>
    </el-row>

    <el-table
      v-loading="loading"
      :data="categoryList"
      row-key="id"
      default-expand-all
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="描述" align="center" prop="id" />
      <el-table-column label="上级分类的编号" align="center" prop="parentId" />
      <el-table-column label="名称" align="center" prop="name" />
      <el-table-column label="分类级别" align="center" prop="level" />
      <el-table-column label="商品数量" align="center" prop="productCount" />
      <el-table-column label="商品单位" align="center" prop="productUnit" />
      <el-table-column label="导航栏" align="center" :formatter="statusFormat" prop="navStatus"   width="200"/>
      <el-table-column label="状态"  :formatter="statusFormat" align="center" prop="showStatus" />
      <el-table-column label="排序" align="center" prop="sort" />
      <el-table-column label="图标" align="center" prop="icon" >
       　<template slot-scope="scope">
　　　　    <img :src="scope.row.icon" width="40" height="40" class="head_pic"/>
　    　</template>
      </el-table-column>
      <el-table-column label="关键字" align="center" prop="keywords" />
      <el-table-column label="描述" align="center" prop="description" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            v-hasPermi="['mall:category:add']"
          >新增</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['mall:category:add']"
          >修改</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 添加或修改商品分类对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="title" :visible.sync="open" width="600px">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="分类级别">
              <el-select v-model="form.level" placeholder="请选择" @change="levelChange">
                <el-option
                  v-for="dict in levelOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="parentShow">
            <el-form-item label="上级分类" prop="parentId">
              <treeselect v-model="form.parentId" :options="categoryOptions" placeholder="选择上级分类" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分类名称" prop="deptName">
              <el-input v-model="form.name" placeholder="请输入分类名称" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="显示排序" prop="orderNum">
              <el-input-number v-model="form.orderNum" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="图标" prop="leader">
              <el-upload
                class="upload-demo"
                :action="fileUrl"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :before-remove="beforeRemove"
                :before-upload="beforeUpload"
                :on-success="handleSuccess"
                multiple
                :headers="fileHeaders"
                :limit="1"
                :name="fileName"
                :on-exceed="handleExceed"
                :file-list="fileList"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> -->
              </el-upload>
              <el-input v-model="form.icon" placeholder="图标" maxlength="20" style="display:none;" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="关键字" prop="phone">
              <el-input v-model="form.keywords" placeholder="请输入关键字" maxlength="11" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示">
              <el-radio-group v-model="form.showStatus">
                <el-radio
                  v-for="dict in statusOptions"
                  :key="dict.dictValue"
                  :label="dict.dictValue"
                >{{dict.dictLabel}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="导航栏">
              <el-radio-group v-model="form.navStatus">
                <el-radio
                  v-for="dict in statusOptions"
                  :key="dict.dictValue"
                  :label="dict.dictValue"
                >{{dict.dictLabel}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listCategory,
  getCategory,
  delCategory,
  addCategory,
  updateCategory,
  exportCategory,
  treeselect,
} from "@/api/mall/category";
import Treeselect from "@riophae/vue-treeselect";
import { getToken } from '@/utils/auth'
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 【请填写功能名称】表格数据
      categoryList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 字典状态
      statusOptions: [],
      levelOptions : [],
      //树形表单
      categoryOptions: undefined,
      // 查询参数
      queryParams: {
        parentId: undefined,
        name: undefined,
        level: undefined,
        productCount: undefined,
        productUnit: undefined,
        navStatus: undefined,
        showStatus: undefined,
        sort: undefined,
        icon: undefined,
        keywords: undefined,
        description: undefined,
      },
      parentShow : false,
      // 表单参数
      form: {
        id: undefined,
        parentId: 0,
        name: undefined,
        level: 1,
        productCount: undefined,
        productUnit: undefined,
        navStatus: "0",
        showStatus: "0",
        sort: undefined,
        icon: undefined,
        keywords: undefined,
        description: undefined,
      },
      
      // 表单校验
      rules: {},
      fileList : [],
      fileName: undefined,
      fileUrl :process.env.VUE_APP_BASE_API+"/minio/upload",
      fileHeaders:  {Authorization: getToken()}
    };
  },
  created() {
    this.getList();
    this.getDicts("sys_on").then((response) => {
      this.statusOptions = response.data;
    });
   this.getDicts("category_level").then(response => {
      this.levelOptions = response.data;
    });
  },
  methods: {
    /** 查询【请填写功能名称】列表 */
    getList() {
      this.loading = true;
      listCategory(this.queryParams).then((response) => {
        this.categoryList = response.data;
        this.loading = false;
      });
    },

    getTreeselect() {
      treeselect().then((response) => {
        this.categoryOptions = response.data;
      });
      console.log( this.categoryOptions);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        parentId: undefined,
        name: undefined,
        level: undefined,
        productCount: undefined,
        productUnit: undefined,
        navStatus: "0",
        showStatus: "0",
        sort: undefined,
        icon: undefined,
        keywords: undefined,
        description: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      this.open = true;
      this.getTreeselect();
      if (row != undefined) {
        this.form.parentId = row.id;
      }
      this.title = "添加商品分类";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getTreeselect();
      const id = row.id || this.ids;
      getCategory(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改商品分类";
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != undefined) {
            updateCategory(this.form).then((response) => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          } else {
            addCategory(this.form).then((response) => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm(
        '是否确认删除商品分类编号为"' + ids + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return delCategory(ids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(function () {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有商品分类数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return exportCategory(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
        })
        .catch(function () {});
    },
     handleRemove(file, fileList) {
        console.log(file, fileList);
      },
      handlePreview(file) {
        console.log(file);
      },
      handleExceed(files, fileList) {
        this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
      },
      beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${ file.name }？`);
      },

      levelChange(value){
        console.log(value);
          if(value != 1){
              this.getTreeselect();
              if(this.categoryOptions === undefined){
                this.$message.warning(`不存在一级分类，请先添加一级分类`);
                // this.from.level = 1;
              return;
              }
               this.parentShow = true;
          }else{
               this.parentShow = false;
               this.from = {parentId:0};
          }

      },
      handleSuccess(response, file, fileList){
        console.log(response);
        console.log(file);
        console.log(fileList);
        if(response.code==200){
            this.form.icon = response.data.etag
        }else{
           this.$message.warning(`文件上传失败！`);
        }
      },
      // 上传预处理
      beforeUpload(file){
      if (file.type.indexOf("image/") == -1) {
        this.msgError("文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。");
      } else {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => {
          this.form.icon = reader.result;
        };
      }
      },
            // 字典状态字典翻译
    statusFormat(row, column) {

      return this.selectDictLabel(this.statusOptions, column.level);
    },
    iconFormat(row,column){
return "<imges src="+row.icon+" width='50px' heigth='50px'>"
    },
  },

};
</script>
